package com.doudanhua.basecode.rabbitmq;

import com.doudanhua.basecode.jackson.JsonConvert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @Author zhangqian
 * @Description TODO
 * @Date 2022/11/8 17:12
 */
@Component
@Slf4j
public class MqHelper {

    private final RabbitTemplate rabbitTemplate;

    public MqHelper(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }


    public void send(String exchange, String key, Object data) {
        try {
            final CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
            rabbitTemplate.convertAndSend(exchange, key, data, correlationData);
            log.debug(String.format("send mq  exchange=%s key=%s data=%s", exchange, key, JsonConvert.toJson(data)));
        } catch (AmqpException e) {
            log.warn(String.format("send mq error exchange=%s key=%s data=%s error=%s", exchange, key, JsonConvert.toJson(data), e.toString()));
        }
    }

    /**
     * 使用延迟插件发送消息方法封装
     * @param exchange
     * @param key
     * @param data
     * @param delayedSeconds
     */
    public void  delayedSend(String exchange,String key,Object data,int delayedSeconds){
        log.info("delaysend:"+ LocalDateTime.now());
        rabbitTemplate.convertAndSend(exchange, key, data, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                ////使用延迟插件只需要在消息的header中添加x-delay属性，值为过期时间，单位毫秒
                message.getMessageProperties().setDelay(delayedSeconds*1000);
                return message;
            }
        });
    }
}
